const { ipcRenderer } = require('electron');

const vueInstance = new Vue({
    el: '#app',
    data() {
        return {
            src: '',
            headers: {},
        };
    },
    methods: {
        initPlayer(onReadyFn) {
            // videojs.Vhs.xhr.beforeRequest = this.beforeVideoRequest;
            const player = videojs('player', {
                plugins: {
                    hotkeys: {
                        // hotkey options
                    },
                },
            }, function() {
                console.debug('Player is ready.');
                if (typeof onReadyFn === 'function') {
                    onReadyFn.call(this);
                }
            });
            return player;
        },
        // 无效，暂时不用
        beforeVideoRequest(options) {
            const headers = options.headers || {};
            Object.assign(headers, JSON.parse(this.headers || '{}'));
            options.headers = headers;
            return options;
        },
        play(src = this.src, headers) {
            this.src = src;
            this.headers = headers;
            const { player } = this;
            const playSrcURL = new URL(src);
            player.src({
                src,
                type: playSrcURL.pathname.endsWith('.mp4') ? 'video/mp4' : 'application/x-mpegURL',
            });
            player.play();
        },
        closePlayer() {
            window.close();
        },
        onSrcChange(src) {
            this.play(src);
        },
    },
    mounted() {
        this.player = this.initPlayer();
    },
    beforeDestroy() {
        this.player && this.player.dispose();
    },
});

ipcRenderer.on('message', (_, { platform, playsrc, headers }) => {
    if (platform && platform == 'darwin') {
        let player = document.querySelector('.header.player');
        player.style.display = 'none';
    }
    if (playsrc) {
        vueInstance.play(playsrc, headers);
    }
});
